package com.mc.moring.widge

import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.AccelerateDecelerateInterpolator
import com.mc.moring.util.StringUtils
import com.mc.moring.util.ext.StringExt.extFormatMoney

class NumberView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatTextView(context, attrs) {

    private var unit: String = "$"

    private var amount:Float = 0F

    fun setAmount(target: Float, isAnim: Boolean = true) {
        this.amount = target
        if (isAnim) {
            startAnim(target)
        } else {
            this.text = "$unit${target.toString().extFormatMoney()}"
        }
    }

    fun setUnit(unit: String) {
        this.unit = unit
    }

    private fun startAnim(target: Float) {
        val old = text?.toString()?.replace("$", "")?.replace(",", "")?.replace(".", "").let {
            if (it.isNullOrEmpty()) 0F else it.toFloat()
        }
        val objectAnimator = ObjectAnimator.ofFloat(old, target)
        objectAnimator.duration = 500
        objectAnimator.interpolator = AccelerateDecelerateInterpolator()
        objectAnimator.addUpdateListener { it ->
//            (it.animatedValue as Float).also { text = "${it.toString().extFormatMoney()}" }
            (it.animatedValue as Float).also { text = "${StringUtils.formatNumberWithCommas(it.toInt().toString())}" }
        }
        objectAnimator.start()
    }

    fun getAmount(): Float {
        return amount
//        try {
//            return text.toString().replace("$", "")?.replace(",", "")?.replace(".", "")?.apply {
//                Log.e("lyd","amount-----"+" "+this)
//            }?.toFloat()
//        } catch (e: Exception) {
//            return null
//        }
    }

}